// pages/admin/app-management/app-management.js
const { authManager } = require('../../../utils/auth');

Page({
  data: {
    applications: [],
    loading: true,
    showModal: false,
    editingApp: null,
    formData: {
      name: '',
      icon: 'icon-app',
      color: '#007aff',
      url: '',
      description: '',
      sort_order: 0
    },
    colorOptions: [
      '#007aff', '#ff3b30', '#ff9500', '#ffcc00', 
      '#34c759', '#5ac8fa', '#af52de', '#ff2d92'
    ],
    iconOptions: [
      'icon-app', 'icon-document', 'icon-user', 'icon-settings',
      'icon-chart', 'icon-calendar', 'icon-message', 'icon-file'
    ]
  },

  onLoad() {
    // 检查管理员权限
    if (!authManager.pageAdminCheck()) {
      return;
    }
    this.loadApplications();
  },
 
    onShareTimeline: function () {
      return {
          title: '分享朋友圈',
          query: 'page=1&size=10',
          imageUrl: '../../../images/tabbar/app.png'
      }
  },
  onShow() {
    // 检查管理员权限
    if (!authManager.pageAdminCheck()) {
      return;
    }
    this.loadApplications();
  },

  // 加载应用列表
  loadApplications() {
    this.setData({ loading: true });

    wx.request({
      url: `${getApp().globalData.serverUrl}/GetAllApplications/`,
      method: 'POST',
      data: {
        admin_username: wx.getStorageSync('username')
      },
      success: (res) => {
        if (res.data.status) {
          // 预处理应用数据
          const applications = res.data.applications.map(app => ({
            ...app,
            displayDescription: app.description || '暂无描述'
          }));

          this.setData({
            applications: applications,
            loading: false
          });
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          });
          this.setData({ loading: false });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    });
  },

  // 显示创建模态框
  showCreateModal() {
    this.setData({
      showModal: true,
      editingApp: null,
      formData: {
        name: '',
        icon: 'icon-app',
        color: '#007aff',
        url: '',
        description: '',
        sort_order: 0
      }
    });
  },

  // 编辑应用
  editApp(e) {
    const appId = e.currentTarget.dataset.id;
    const app = this.data.applications.find(item => item.id === appId);
    
    if (app) {
      this.setData({
        showModal: true,
        editingApp: app,
        formData: {
          name: app.name,
          icon: app.icon,
          color: app.color,
          url: app.url || '',
          description: app.description || '',
          sort_order: app.sort_order || 0
        }
      });
    }
  },

  // 切换应用状态
  toggleStatus(e) {
    const appId = e.currentTarget.dataset.id;
    const app = this.data.applications.find(item => item.id === appId);
    
    if (!app) return;

    wx.showModal({
      title: '确认操作',
      content: `确定要${app.is_active ? '禁用' : '启用'}应用"${app.name}"吗？`,
      success: (res) => {
        if (res.confirm) {
          this.performToggleStatus(appId);
        }
      }
    });
  },

  // 执行状态切换
  performToggleStatus(appId) {
    wx.showLoading({ title: '处理中...' });

    wx.request({
      url: `${getApp().globalData.serverUrl}/ToggleApplicationStatus/`,
      method: 'POST',
      data: {
        admin_username: wx.getStorageSync('username'),
        application_id: appId
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.status) {
          wx.showToast({
            title: res.data.message,
            icon: 'success'
          });
          this.loadApplications();
        } else {
          wx.showToast({
            title: res.data.message || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 表单输入
  onInput(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    this.setData({
      [`formData.${field}`]: field === 'sort_order' ? parseInt(value) || 0 : value
    });
  },

  // 选择颜色
  selectColor(e) {
    const color = e.currentTarget.dataset.color;
    this.setData({
      'formData.color': color
    });
  },

  // 选择图标
  selectIcon(e) {
    const icon = e.currentTarget.dataset.icon;
    this.setData({
      'formData.icon': icon
    });
  },

  // 保存应用
  saveApp() {
    const { formData, editingApp } = this.data;
    
    if (!formData.name.trim()) {
      wx.showToast({
        title: '请输入应用名称',
        icon: 'none'
      });
      return;
    }

    const isEdit = !!editingApp;
    const url = isEdit 
      ? `${getApp().globalData.serverUrl}/UpdateApplication/`
      : `${getApp().globalData.serverUrl}/CreateApplication/`;

    const requestData = {
      admin_username: wx.getStorageSync('username'),
      ...formData
    };

    if (isEdit) {
      requestData.application_id = editingApp.id;
    }

    wx.showLoading({ title: isEdit ? '更新中...' : '创建中...' });

    wx.request({
      url: url,
      method: 'POST',
      data: requestData,
      success: (res) => {
        wx.hideLoading();
        if (res.data.status) {
          wx.showToast({
            title: res.data.message,
            icon: 'success'
          });
          this.setData({ showModal: false });
          this.loadApplications();
        } else {
          wx.showToast({
            title: res.data.message || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 关闭模态框
  closeModal() {
    this.setData({ showModal: false });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡，防止点击模态框内容时关闭模态框
  }
});